#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <dirent.h>

blkcnt_t traverseDir(char* entryName);

int main(int argc, char* argv[])
{
    blkcnt_t totalSize = 0;
    if (argc != 2) {
        printf("Uasge: %s <path>\n", argv[0]);
        return 1;
    }

    totalSize = traverseDir(argv[1]);
    printf("total: %ld\n", totalSize);
    return 0;
}

blkcnt_t traverseDir(char* entryName)
{
    DIR* dir;
    struct dirent* newEntry;
    blkcnt_t totalSize = 0;

    if (entryName == NULL) {
        printf("path is null\n");
        return 0;
    }

    dir = opendir(entryName);
    if (!dir) {
        perror(entryName);
        return 0;
    }

    while (newEntry = readdir(dir)) {
        if (strcmp(newEntry->d_name, ".") == 0 || strcmp(newEntry->d_name, "..") == 0) {
            continue;
        }

        if (newEntry->d_type == DT_DIR) {
            struct stat st;
            char path[PATH_MAX];

            sprintf(path, "%s/%s", entryName, newEntry->d_name);
            if (lstat(path, &st)) {
                perror(path);
                return 0;
            }

            totalSize += st.st_size;
            //printf("total=%ld size=%ld file=%s\n", totalSize, st.st_size, path);
            totalSize += traverseDir(path);
        } else {
            // file
            struct stat st;
            char path[PATH_MAX];
            sprintf(path, "%s/%s", entryName, newEntry->d_name);

            if (lstat(path, &st)) {
                perror(path);
                return 0;
            }
            // totalSize += st.st_blocks;
            totalSize += st.st_size;
            // printf("total=%ld size=%ld file=%s \n", totalSize, st.st_size, path);
        }
    }

    return totalSize;
}

#if 0
blkcnt_t TraverseDir(char* entryName, int maxDepthFlag, int maxDepthValue)
{
    blkcnt_t totalSize = 0;
    struct stat st;
    char buffer[PATH_MAX];
    DIR* dir;
    struct dirent* newEntry;

    /* 如果目录名称错误或路径不正确 */
    if (lstat(entryName, &st)) {
        perror(entryName);
        exit(-1);
    }

    /* 用于打开和遍历目录  */
    if (S_ISDIR(st.st_mode) && (dir = opendir(entryName))) {
        while ((newEntry = readdir(dir)))
            if (strcmp(newEntry->d_name, ".") && strcmp(newEntry->d_name, "..")) {
                snprintf(buffer, PATH_MAX, "%s/%s", entryName, newEntry->d_name);
                /* 递归调用函数直到 maxDepthValue 变为 0  */
                totalSize += TraverseDir(buffer, maxDepthFlag, maxDepthValue - 1);
            }
        closedir(dir);
    }

    /* 添加块大小  */
    totalSize += st.st_blocks;

    return totalSize; /* 返回块数  */
}
#endif
